package sist.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.FileCopyUtils;
import org.springframework.web.servlet.view.AbstractView;

public class DownloadView extends AbstractView{
	
	@Override
	protected void renderMergedOutputModel(Map<String, Object> model,
			HttpServletRequest requset, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		File file=(File)model.get("downloadFile");
		response.setContentType(this.getContentType());
		response.setContentLength((int)file.length());
		String userAgent=requset.getHeader("User-Agent");
		String fileName="";
		if(!(userAgent.indexOf("Chrome")>-1)){
			fileName=URLEncoder.encode(file.getName(), "UTF-8");
		}else{
			fileName=new String(file.getName().getBytes());
		}
		response.setHeader("Content-Disposition","attachment;fileName=\""+fileName+"\";");
		response.setHeader("Content-Transfer-Encoding", "binary");
		
		OutputStream out=response.getOutputStream();
		FileInputStream fis=null;
		fis=new FileInputStream(file);
		FileCopyUtils.copy(fis, out);
		out.flush();		
	}
}
